import React, { useState, useEffect } from 'react';
import { Card, Descriptions, Button, Modal, Form, InputNumber, Table, Tabs, Spin, Space, Row, Col, Statistic, App } from 'antd';
import { ArrowLeftOutlined, EditOutlined, WalletOutlined, TrophyOutlined, HistoryOutlined } from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';
import userService from '../../services/userService';
import type { User, BalanceRecord, PaginationParams } from '../../services/userService';
import { getFormattedErrorMessage } from '../../services/baseApi';

const { TabPane } = Tabs;

const UserDetailPage: React.FC = () => {
    const { id } = useParams<{ id: string }>();
    const navigate = useNavigate();
    const [user, setUser] = useState<User | null>(null);
    const [loading, setLoading] = useState(false);
    const [balanceModalVisible, setBalanceModalVisible] = useState(false);
    const [creditModalVisible, setCreditModalVisible] = useState(false);
    const [balanceRecords, setBalanceRecords] = useState<BalanceRecord[]>([]);
    const [creditRecords, setCreditRecords] = useState<BalanceRecord[]>([]);
    const [balanceRecordsLoading, setBalanceRecordsLoading] = useState(false);
    const [creditRecordsLoading, setCreditRecordsLoading] = useState(false);
    const [balanceForm] = Form.useForm();
    const [creditForm] = Form.useForm();
    const [activeTab, setActiveTab] = useState('balance');

    const { message } = App.useApp();

    const userId = id ? parseInt(id) : 0;

    // 加载用户详情
    const loadUserDetail = async () => {
        if (!userId) return;
        setLoading(true);
        try {
            const response = await userService.getUserDetail(userId);
            if (response.code === 0) {
                setUser(response.data);
                // 重置表单，不预填充当前值
                balanceForm.resetFields();
                creditForm.resetFields();
            } else {
                message.error(response.message || '获取用户详情失败');
            }
        } catch (error) {
            message.error(getFormattedErrorMessage(error));
        } finally {
            setLoading(false);
        }
    };

    // 加载余额记录
    const loadBalanceRecords = async (params?: PaginationParams) => {
        if (!userId) return;
        setBalanceRecordsLoading(true);
        try {
            const response = await userService.getUserBalanceRecords(userId, params);
            if (response.code === 0) {
                setBalanceRecords(response.data.list);
            } else {
                message.error(response.message || '获取余额记录失败');
            }
        } catch (error) {
            message.error(getFormattedErrorMessage(error));
        } finally {
            setBalanceRecordsLoading(false);
        }
    };

    // 加载积分记录
    const loadCreditRecords = async (params?: PaginationParams) => {
        if (!userId) return;
        setCreditRecordsLoading(true);
        try {
            const response = await userService.getUserCreditRecords(userId, params);
            if (response.code === 0) {
                setCreditRecords(response.data.list);
            } else {
                message.error(response.message || '获取积分记录失败');
            }
        } catch (error) {
            message.error(getFormattedErrorMessage(error));
        } finally {
            setCreditRecordsLoading(false);
        }
    };

    // 调整余额（支持正负数）
    const handleAdjustBalance = async (values: { amount: number }) => {
        if (!user) return;
        try {
            // 计算新的余额值
            const newBalance = values.amount;

            const response = await userService.updateUserBalance(userId, { balance: newBalance });
            if (response.code === 0) {
                message.success(`余额${values.amount > 0 ? '增加' : '减少'}成功`);
                setBalanceModalVisible(false);
                loadUserDetail();
                loadBalanceRecords();
            } else {
                message.error(response.message || '调整余额失败');
            }
        } catch (error) {
            message.error(getFormattedErrorMessage(error));
        }
    };

    // 调整积分（支持正负数）
    const handleAdjustCredit = async (values: { amount: number }) => {
        if (!user) return;
        try {
            // 计算新的积分值
            const newCredit = values.amount;

            const response = await userService.updateUserCredit(userId, { credit: newCredit });
            if (response.code === 0) {
                message.success(`积分${values.amount > 0 ? '增加' : '减少'}成功`);
                setCreditModalVisible(false);
                loadUserDetail();
                loadCreditRecords();
            } else {
                message.error(response.message || '调整积分失败');
            }
        } catch (error) {
            message.error(getFormattedErrorMessage(error));
        }
    };

    // 页面初始化
    useEffect(() => {
        loadUserDetail();
        // 初始化时加载记录
        loadBalanceRecords();
        loadCreditRecords();
    }, [userId]);

    // Tab切换时加载对应记录
    const handleTabChange = (key: string) => {
        setActiveTab(key);
        if (key === 'balance') {
            loadBalanceRecords();
        } else if (key === 'credit') {
            loadCreditRecords();
        }
    };

    // 记录表格列定义
    const recordColumns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            width: 80,
        },
        {
            title: '变动金额',
            dataIndex: 'amount',
            key: 'amount',
            width: 120,
            render: (amount: number) => (
                <span style={{
                    color: amount > 0 ? '#52c41a' : '#ff4d4f',
                    fontWeight: 'bold'
                }}>
                    {amount > 0 ? '+' : ''}{amount}
                </span>
            ),
        },
        {
            title: '创建时间',
            dataIndex: 'createdAt',
            key: 'createdAt',
            width: 180,
            render: (date: string) => new Date(date).toLocaleString(),
        },
        {
            title: '更新时间',
            dataIndex: 'updatedAt',
            key: 'updatedAt',
            width: 180,
            render: (date: string) => new Date(date).toLocaleString(),
        },
    ];

    if (!user && !loading) {
        return (
            <div style={{ padding: '24px', textAlign: 'center' }}>
                <p>用户不存在</p>
                <Button onClick={() => navigate('/users')}>返回用户列表</Button>
            </div>
        );
    }

    return (
        <div style={{ padding: '24px', backgroundColor: '#f5f5f5', minHeight: '100vh' }}>
            <Spin spinning={loading}>
                {/* 页面头部 */}
                <div style={{
                    marginBottom: '24px',
                    backgroundColor: 'white',
                    padding: '16px 24px',
                    borderRadius: '8px',
                    boxShadow: '0 1px 3px rgba(0,0,0,0.1)',
                    display: 'flex',
                    alignItems: 'flex-start',
                }}>
                    <Button
                        icon={<ArrowLeftOutlined />}
                        onClick={() => navigate('/users')}
                        style={{ marginRight: '16px' }}
                    >
                        返回
                    </Button>
                    <span style={{ fontSize: '20px', fontWeight: 'bold', color: '#333' }}>用户详情</span>
                </div>

                {user && (
                    <>
                        {/* 基本信息和关键数据 */}
                        <Row gutter={[24, 24]} style={{ marginBottom: '24px' }}>
                            {/* 用户基本信息 */}
                            <Col xs={24} lg={16}>
                                <Card
                                    title="基本信息"
                                    style={{ height: '100%' }}
                                    headStyle={{ backgroundColor: '#fafafa', borderBottom: '1px solid #f0f0f0' }}
                                >
                                    <Descriptions column={1} size="middle">
                                        <Descriptions.Item label="用户ID" labelStyle={{ fontWeight: 'bold', color: '#666' }}>
                                            <span style={{ fontSize: '16px' }}>{user.id}</span>
                                        </Descriptions.Item>
                                        <Descriptions.Item label="UUID" labelStyle={{ fontWeight: 'bold', color: '#666' }}>
                                            <span style={{
                                                fontFamily: 'monospace',
                                                fontSize: '13px',
                                                padding: '4px 8px',
                                                backgroundColor: '#f5f5f5',
                                                borderRadius: '4px'
                                            }}>
                                                {user.uuid}
                                            </span>
                                        </Descriptions.Item>
                                        <Descriptions.Item label="用户名" labelStyle={{ fontWeight: 'bold', color: '#666' }}>
                                            <span style={{ fontSize: '16px', fontWeight: '500' }}>{user.username}</span>
                                        </Descriptions.Item>
                                        <Descriptions.Item label="手机号" labelStyle={{ fontWeight: 'bold', color: '#666' }}>
                                            <span style={{ fontSize: '16px' }}>{user.mobile || '-'}</span>
                                        </Descriptions.Item>
                                    </Descriptions>
                                </Card>
                            </Col>

                            {/* 余额和积分统计 */}
                            <Col xs={24} lg={8}>
                                <Card
                                    title="账户资产"
                                    style={{ height: '100%' }}
                                    headStyle={{ backgroundColor: '#fafafa', borderBottom: '1px solid #f0f0f0' }}
                                >
                                    <Space direction="vertical" size="large" style={{ width: '100%' }}>
                                        <div style={{ textAlign: 'center', padding: '12px', backgroundColor: '#f6ffed', borderRadius: '8px' }}>
                                            <Statistic
                                                title="账户余额"
                                                value={user.balance}
                                                precision={2}
                                                prefix="¥"
                                                valueStyle={{ color: '#52c41a', fontSize: '24px', fontWeight: 'bold' }}
                                            />
                                            <Button
                                                type="primary"
                                                size="small"
                                                icon={<EditOutlined />}
                                                onClick={() => setBalanceModalVisible(true)}
                                                style={{ marginTop: '8px' }}
                                            >
                                                调整余额
                                            </Button>
                                        </div>

                                        <div style={{ textAlign: 'center', padding: '12px', backgroundColor: '#f0f8ff', borderRadius: '8px' }}>
                                            <Statistic
                                                title="会员积分"
                                                value={user.credit}
                                                valueStyle={{ color: '#1890ff', fontSize: '24px', fontWeight: 'bold' }}
                                            />
                                            <Button
                                                type="primary"
                                                size="small"
                                                icon={<EditOutlined />}
                                                onClick={() => setCreditModalVisible(true)}
                                                style={{ marginTop: '8px' }}
                                            >
                                                调整积分
                                            </Button>
                                        </div>
                                    </Space>
                                </Card>
                            </Col>
                        </Row>

                        {/* 变动记录 */}
                        <Card
                            title="变动记录"
                            style={{ backgroundColor: 'white' }}
                            headStyle={{ backgroundColor: '#fafafa', borderBottom: '1px solid #f0f0f0' }}
                        >
                            <Tabs activeKey={activeTab} onChange={handleTabChange}>
                                <TabPane
                                    tab={
                                        <span>
                                            <WalletOutlined />
                                            余额记录
                                        </span>
                                    }
                                    key="balance"
                                >
                                    <div style={{ marginBottom: '16px', display: 'flex', justifyContent: 'flex-end' }}>
                                        <Button
                                            icon={<HistoryOutlined />}
                                            onClick={() => loadBalanceRecords()}
                                            loading={balanceRecordsLoading}
                                        >
                                            刷新记录
                                        </Button>
                                    </div>
                                    <Table
                                        columns={recordColumns}
                                        dataSource={balanceRecords}
                                        rowKey="id"
                                        loading={balanceRecordsLoading}
                                        pagination={{
                                            pageSize: 10,
                                            showSizeChanger: true,
                                            showQuickJumper: true,
                                            showTotal: (total, range) => `第 ${range?.[0]}-${range?.[1]} 条/共 ${total} 条`,
                                        }}
                                        locale={{ emptyText: '暂无余额变动记录' }}
                                    />
                                </TabPane>
                                <TabPane
                                    tab={
                                        <span>
                                            <TrophyOutlined />
                                            积分记录
                                        </span>
                                    }
                                    key="credit"
                                >
                                    <div style={{ marginBottom: '16px', display: 'flex', justifyContent: 'flex-end' }}>
                                        <Button
                                            icon={<HistoryOutlined />}
                                            onClick={() => loadCreditRecords()}
                                            loading={creditRecordsLoading}
                                        >
                                            刷新记录
                                        </Button>
                                    </div>
                                    <Table
                                        columns={recordColumns}
                                        dataSource={creditRecords}
                                        rowKey="id"
                                        loading={creditRecordsLoading}
                                        pagination={{
                                            pageSize: 10,
                                            showSizeChanger: true,
                                            showQuickJumper: true,
                                            showTotal: (total, range) => `第 ${range?.[0]}-${range?.[1]} 条/共 ${total} 条`,
                                        }}
                                        locale={{ emptyText: '暂无积分变动记录' }}
                                    />
                                </TabPane>
                            </Tabs>
                        </Card>
                    </>
                )}
            </Spin>

            {/* 调整余额弹窗 */}
            <Modal
                title="调整余额"
                open={balanceModalVisible}
                onCancel={() => setBalanceModalVisible(false)}
                footer={null}
                width={500}
            >
                {user && (
                    <div style={{ marginBottom: '16px', padding: '12px', backgroundColor: '#f5f5f5', borderRadius: '6px' }}>
                        <span style={{ color: '#666' }}>当前余额: </span>
                        <span style={{ color: '#52c41a', fontWeight: 'bold', fontSize: '16px' }}>
                            ¥{user.balance.toFixed(2)}
                        </span>
                    </div>
                )}
                <Form
                    form={balanceForm}
                    layout="vertical"
                    onFinish={handleAdjustBalance}
                >
                    <Form.Item
                        label="调整金额"
                        name="amount"
                        help="输入正数表示增加余额，输入负数表示减少余额"
                        rules={[
                            { required: true, message: '请输入调整金额' },
                            { type: 'number', message: '请输入有效数字' },
                            {
                                validator: (_, value) => {
                                    if (!user) return Promise.resolve();
                                    const newBalance = user.balance + (value || 0);
                                    if (newBalance < 0) {
                                        return Promise.reject(new Error('调整后余额不能为负数'));
                                    }
                                    return Promise.resolve();
                                }
                            }
                        ]}
                    >
                        <InputNumber
                            style={{ width: '100%' }}
                            precision={2}
                            placeholder="输入调整金额，如: +100 或 -50"
                            addonBefore="±"
                        />
                    </Form.Item>
                    <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
                        <Space>
                            <Button onClick={() => setBalanceModalVisible(false)}>
                                取消
                            </Button>
                            <Button type="primary" htmlType="submit">
                                确定调整
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Modal>

            {/* 调整积分弹窗 */}
            <Modal
                title="调整积分"
                open={creditModalVisible}
                onCancel={() => setCreditModalVisible(false)}
                footer={null}
                width={500}
            >
                {user && (
                    <div style={{ marginBottom: '16px', padding: '12px', backgroundColor: '#f5f5f5', borderRadius: '6px' }}>
                        <span style={{ color: '#666' }}>当前积分: </span>
                        <span style={{ color: '#1890ff', fontWeight: 'bold', fontSize: '16px' }}>
                            {user.credit}
                        </span>
                    </div>
                )}
                <Form
                    form={creditForm}
                    layout="vertical"
                    onFinish={handleAdjustCredit}
                >
                    <Form.Item
                        label="调整积分"
                        name="amount"
                        help="输入正数表示增加积分，输入负数表示减少积分"
                        rules={[
                            { required: true, message: '请输入调整积分' },
                            { type: 'number', message: '请输入有效数字' },
                            {
                                validator: (_, value) => {
                                    if (!user) return Promise.resolve();
                                    const newCredit = user.credit + (value || 0);
                                    if (newCredit < 0) {
                                        return Promise.reject(new Error('调整后积分不能为负数'));
                                    }
                                    return Promise.resolve();
                                }
                            }
                        ]}
                    >
                        <InputNumber
                            style={{ width: '100%' }}
                            precision={0}
                            placeholder="输入调整积分，如: +200 或 -100"
                            addonBefore="±"
                        />
                    </Form.Item>
                    <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
                        <Space>
                            <Button onClick={() => setCreditModalVisible(false)}>
                                取消
                            </Button>
                            <Button type="primary" htmlType="submit">
                                确定调整
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default UserDetailPage; 